package db.migration;

import java.sql.Timestamp;

import org.flywaydb.core.api.migration.spring.BaseSpringJdbcMigration;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.baomidou.mybatisplus.toolkit.IdWorker;

import net.jiastudy.biz.user.entity.User;
import net.jiastudy.core.common.SysRole;

public class V1_0_1__init extends BaseSpringJdbcMigration {

	private JdbcTemplate jdbcTemplate;

	@Override
	public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
		this.jdbcTemplate = jdbcTemplate;
		this.saveUser();
	}

	private void saveUser() {
		Long adminRoleid = IdWorker.getId();
		jdbcTemplate.update(
				"insert into role (id, code, name, sys_role, create_date , last_modified) VALUES (?, ?, ?, ?, ?, ?)",
				new Object[] { adminRoleid, SysRole.ROLE_SUPER_ADMIN.name(), "超级管理员", true,
						new Timestamp(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()) });

		RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
		User user = null;
		try {
			user = jdbcTemplate.queryForObject("select id,username,name from user where username=?", rowMapper,
					"admin");
		} catch (EmptyResultDataAccessException e) {
			user = null;
		}

		Long adminUserid = IdWorker.getId();
		if (null == user) {
			String password = new BCryptPasswordEncoder().encode("jiastudyadmin");

			jdbcTemplate.update(
					"insert into user (id, username, nickname, name, email, password, create_date , last_modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
					new Object[] { adminUserid, "admin", "超级管理员", "超级管理员", "admin@jiastudy.net", password,
							new Timestamp(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()) });
		} else {
			adminUserid = user.getId();
		}

		Long userRoleId = IdWorker.getId();
		jdbcTemplate.update(
				"insert into user_role (id, user_id, role_id, create_date, last_modified) VALUES (?, ?, ?, ?, ?)",
				new Object[] { userRoleId, adminUserid, adminRoleid, new Timestamp(System.currentTimeMillis()),
						new Timestamp(System.currentTimeMillis()) });
	}
}
